<template>
	<div class="editor-container" :style="{ width }">
		<Toolbar :editor="editorRef" :mode="mode" :defaultConfig="config" />
		<WEditor :mode="mode" :defaultConfig="editorConfig" :style="{ height }" v-model="editValue"
			@onCreated="handleCreated" @onChange="handleChange" />
	</div>
	<uploadAttachment ref="attachmentRef" :limit="attachmentConfig.limit" :type="attachmentConfig.type"
		@confirm="uploadConfirm" />
</template>

<script setup lang="ts" name="wngEditor">
import '@wangeditor/editor/dist/css/style.css';
import { ref, reactive, computed, shallowRef, watch, onBeforeUnmount } from 'vue';
import { IDomEditor } from '@wangeditor/editor';
import { Toolbar, Editor as WEditor } from '@wangeditor/editor-for-vue';
import { getFileOrder } from '/@/utils/util';

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	// 是否禁用
	disable: {
		type: Boolean,
		default: false,
	},
	// 内容框默认 placeholder
	placeholder: {
		type: String,
		default: '请输入内容...',
	},
	// 模式，可选 <default|simple>，默认 default
	mode: {
		type: String,
		default: 'default',
	},
	// 高度
	width: {
		type: String,
		default: '',
	},
	// 高度
	height: {
		type: String,
		default: '320px',
	},
	// 配置
	config: {
		type: Object,
		default: {},
	},
	// 获取文本内容
	getText: String,
});

const editorRef = shallowRef();

const emit = defineEmits(['update:modelValue', 'update:getHtml', 'update:getText']);

const attachmentRef = ref(null);

const attachmentConfig = reactive({
	type: '',
	limit: 5,
});

let insertFn: any;

const editorConfig = reactive({
	placeholder: props.placeholder,
	MENU_CONF: {
		uploadImage: {
			customBrowseAndUpload(insert: any) {
				attachmentConfig.type = 'image';
				attachmentRef.value.openDialog();
				insertFn = insert;
			},
		},
		uploadVideo: {
			customBrowseAndUpload(insert: any) {
				attachmentConfig.type = 'video';
				attachmentRef.value.openDialog();
				insertFn = insert;
			},
		},
	},
});

const editValue = computed({
	get() {
		return props.modelValue;
	},
	set(value) {
		emit('update:modelValue', value);
	},
});

// 编辑器回调函数
const handleCreated = (editor: IDomEditor) => {
	editorRef.value = editor;
};
// 编辑器内容改变时
const handleChange = (editor: IDomEditor) => {
	emit('update:getText', editor.getText());
};

// 附件组件选择完成
const uploadConfirm = (data: Record<string, any>) => {
	if (attachmentConfig.limit <= 1) {
		insertFn(data[0].uri);
	} else {
		const data_order = getFileOrder(data); //重新排序
		data_order.forEach((item) => {
			insertFn(item.uri);
		});
	}
};

// 页面销毁时
onBeforeUnmount(() => {
	const editor = editorRef.value;
	if (editor == null) return;
	editor.destroy();
});

// 监听是否禁用改变
watch(
	() => props.disable,
	(bool) => {
		const editor = editorRef.value;
		if (editor == null) return;
		bool ? editor.disable() : editor.enable();
	},
	{
		deep: true,
	}
);
</script>

<style lang="scss" scoped>
	.editor-container {
		z-index: 999;
	}
</style>
